package com.hp.bon.sgw.wh.bean.tmall;

import java.rmi.RemoteException;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringEscapeUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.alibaba.fastjson.JSON;
import com.hp.bon.sgw.wh.bean.MonthlyBillError;

/** 
 * CopyRright (c)2016/12-:SGW_WH2.1_TMALL_20180102
 * Project:SGW_WH2.1_TMALL_20180102
 * Module ID:Test
 * Comments:TODO
 * @author :chenjun  
 * Create Date：2018年1月3日
 * Modified By：Chenjun                     
 * Modified Date:2018年1月3日
 * Why:TODO
 * Version:<v1.0> 
 */
public class Test {
   public static void main(String[] args) throws DocumentException, RemoteException {
	  /* List<com.hp.bon.sgw.wh.bean.Invoice> invoiceList = new ArrayList<com.hp.bon.sgw.wh.bean.Invoice>();
	   com.hp.bon.sgw.wh.bean.Invoice invoice = new com.hp.bon.sgw.wh.bean.Invoice();
	   invoice.setInvoiceCode("1");
	   	invoice.setInvoiceDate("1");
	   	invoice.setInvoiceId("1");
	   	invoice.setInvoideNo("1");
	   	invoice.setType("1");
	   	invoice.setValue("1");
	   	invoice.setUrl("1");
	   	invoiceList.add(invoice);
	   	String jsonStr = JSON.toJSONString(invoiceList);
	   	jsonStr = jsonStr.replaceAll("\\[", "");
	   	jsonStr = jsonStr.replaceAll("\\]", "");
	   	System.out.println(jsonStr);*/
	   	
	  /* String s = "test";
	   
	   System.out.println(s.split("_")[0]);*/
	   
	 /*   List<com.hp.bon.sgw.wh.bean.InvoiceInformation> invoiceInformationList = new ArrayList<com.hp.bon.sgw.wh.bean.InvoiceInformation>();
	    String resp = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><soapenv:Body><QueryEInvoiceDetailResponse xmlns=\"http://ygz.service.boss/client/\"><RESULT>0</RESULT><id>31000100685</id><custId>30020100685</custId><mobile>15926882674</mobile><eMail>396792420@qq.com</eMail><automaticPush>1</automaticPush><lanId>8430101</lanId><invoiceHeader>襄阳港务发展有限公司</invoiceHeader><buyerTaxPayerId>914206007146798797</buyerTaxPayerId></QueryEInvoiceDetailResponse></soapenv:Body></soapenv:Envelope>";
	    //String resp =  StringEscapeUtils.unescapeXml(getWebserviceStr(buildStringMes, webserviceUrl));
		String result = "0";
		String jsonStr = "";
	    //response.set("X-CTG-Request-ID", value);
	    //response.set("X-RateLimit-Limit", "60");
	    //response.set("X-RateLimit-Remaining", "48");
	    //response.set("X-RateLimit-Reset", "14");
		if(!resp.equals("")) {
			    //_log.info("=======================resp========================"+resp);
			//_log.info("=======================resp========================"+resp);
		    Document doc = null;
		    doc = DocumentHelper.parseText(resp);
		    Element node = doc.getRootElement();
		    List<Element> element = getElement(node);
		    String id = "";
		    String custId = "";
	    	String mobile = "";
	    	String eMail = "";
	    	String automaticPush = "";
	    	String lanIds = "";
	    	String invoiceHeader = "";
	    	String buyerTaxPayerId = "";
	    	com.hp.bon.sgw.wh.bean.InvoiceInformation information = new com.hp.bon.sgw.wh.bean.InvoiceInformation();
		    for (int j = 0; j < element.size(); j++) {
		      Element element2 = element.get(j);
		      String name = element2.getName();
	    	  if(name.equals("RESULT")) {
	    		  result = element2.getText();
	    	  }
	    	  if(name.equals("id")) {
	    		  id = element2.getText();
	    	  }
			  if(name.equals("custId")) {
				  custId = element2.getText();	    		  
			  }
			  if(name.equals("mobile")) {
				  mobile = element2.getText();
			  }
			  if(name.equals("eMail")) {
				  eMail = element2.getText();
			  }
			  if(name.equals("automaticPush")) {
				  automaticPush = element2.getText();
			  }
              if(name.equals("lanId")) {
            	  lanIds = element2.getText();
			  }
			  if(name.equals("invoiceHeader")) {
				  invoiceHeader = element2.getText();
			  }
			  if(name.equals("buyerTaxPayerId")) {
				  buyerTaxPayerId = element2.getText();
			  }
	    	  
		    }
		    information.setAutomaticPush(automaticPush);
	        information.setBuyerTaxPayerId(buyerTaxPayerId);
	    	information.setCustId(custId);
	    	information.seteMail(eMail);
	    	information.setId(id);
	    	information.setInvoiceHeader(invoiceHeader);
	        information.setLanId(lanIds);
	    	information.setMobile(mobile);
	    	invoiceInformationList.add(information);
		    if(!result.equals("0")) {
		    	List<MonthlyBillError> monthlyBillErrorList = new ArrayList<MonthlyBillError>();
		    	MonthlyBillError monthlyBillError = new MonthlyBillError();
		    	monthlyBillError.setCode(result);
		    	monthlyBillError.setMessage("");
		    	monthlyBillError.setReason("");
		    	monthlyBillError.setReferenceError("");
		    	monthlyBillErrorList.add(monthlyBillError);
		    	jsonStr = JSON.toJSONString(monthlyBillErrorList);
		    }
		    else {
			    //_log.info("=======================resp111========================"+resp);
			    jsonStr = JSON.toJSONString(invoiceInformationList);
			    //_log.info("=======================respXMLJSON========================");
			    //_log.info("---返回的消息---"+jsonStr);
			    //_log.info("=======================respXML========================");
		    }
	}
	else {
		List<MonthlyBillError> monthlyBillErrorList = new ArrayList<MonthlyBillError>();
		MonthlyBillError monthlyBillError = new MonthlyBillError();
    	monthlyBillError.setCode(result);
    	monthlyBillError.setMessage("");
    	monthlyBillError.setReason("");
    	monthlyBillError.setReferenceError("");
    	monthlyBillErrorList.add(monthlyBillError);
    	jsonStr = JSON.toJSONString(monthlyBillErrorList);
	}*/
	   
	    /*String str = "[{\"columnId\":\"5\",\"columnName\":\"人文历史\"},{\"columnId\":\"2\",\"columnName\":\"商业视野\"}]";
	    com.alibaba.fastjson.JSONArray jsonObject = JSON.parseArray(str);
	    StringBuilder buildStringMes = new StringBuilder();
		buildStringMes.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://ws.hquery.ailk.com/\">");
		buildStringMes.append("<soapenv:Header/>");
		buildStringMes.append("<soapenv:Body>");
		buildStringMes.append("<m:UpdateDrawInfoRequest xmlns:m=\"http://ygz.service.boss/client/\">");
		buildStringMes.append("<m:lanId>"+1300851+"</m:lanId>");
		buildStringMes.append("<m:serialNumber>"+842000+"</m:serialNumber>");
	    for (int i = 0; i < jsonObject.size(); i++){
	    	com.alibaba.fastjson.JSONObject s1 = jsonObject.getJSONObject(i);
	    	buildStringMes.append("<m:ITEM>");
	    	buildStringMes.append("<m:op>"+s1.get("columnId")+"</m:op>");
	    	buildStringMes.append("<m:path>"+s1.get("columnName")+"</m:path>");
	    	buildStringMes.append("</m:ITEM>");
	    	
	    }
		buildStringMes.append("</m:UpdateDrawInfoRequest>");
		buildStringMes.append("</soapenv:Body>");
		buildStringMes.append("</soapenv:Envelope>");*/
	  
	    //com.alibaba.fastjson.JSONArray family =jsonObject.getJSONArray("columnId");
		//System.out.println(buildStringMes.toString());
		//System.out.println(jsonStr);
	  /* String s ="{\"type\": \"1000\",\"lanId\": \"8500100\",\"invoiceId\": \"1\",\"object\": {\"id\": \"32312456\",\"productId\": \"11111\",\"billMonth\": \"201802\",\"amount\": \"50\",\"status\": \"1\"}}";
	   JSONObject object=JSONObject.fromObject(s);
	   System.out.println(object.getJSONObject("object").get("id"));
	   System.out.println(object.getString("issueId"));*/
	   /*String s = "/ws/SGWService/invoice";
	   System.out.println(s.endsWith("invoice"));*/
	               /* int num1 = 2;  
	   
	                int num2 = 3;  
	               // 创建一个数值格式化对象  
	        
	                NumberFormat numberFormat = NumberFormat.getInstance();  
	         
	                // 设置精确到小数点后2位  
	         
	                numberFormat.setMaximumFractionDigits(2);  
	         
	                String result = numberFormat.format((float) num1 / (float) num2 * 100);  
	         
	                System.out.println("num1和num2的百分比为:" + result + "%");*/


	   //Map resultMap=sortMapByKey(map);//按Key进行排序


	   /*for(Map.Entry entry:resultMap.entrySet()){
	        System.out.println(entry.getKey()+""+entry.getValue());
	   }*/
	   
	   /*String s = "select * from (select * from (select * from (select * from (select * from hss_web_permission) where rownum<=50) where rownum<=100) where rownum<=150) where rownum<=200";
	   System.out.println(s.substring(0,6) + " count(1) " + s.substring(s.indexOf("from")));
	   String fromFrontStr = s.substring(0,s.lastIndexOf("rownum"));
	   System.out.println(fromFrontStr);*/
	   List<com.hp.bon.sgw.wh.bean.Invoice> invoiceList = new ArrayList<com.hp.bon.sgw.wh.bean.Invoice>();
	   String resp = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><soapenv:Body><QueryEInvoiceDetailResponse xmlns=\"http://ygz.service.boss/client/\"><RESULT>0</RESULT><url>http://10.140.19.179:9091/yys-dx-download/downloadController/download?request=38dCJttvTWcfd5YZh77ALaBqaY0e39C8sBad0-WtBxM19wS9siQuxhOQFKBlxEErUrJWXMulB4qXbuZvKPtckg__%5EcgFeHCCCgj&source=JTWT</url><invoiceDate>2019-01-28T01:01:26.000Z</invoiceDate><invoiceCode>042001800211</invoiceCode><invoiceNo>19723136</invoiceNo><invoiceId>1001110488364543</invoiceId><value>16920</value><type>1000</type></QueryEInvoiceDetailResponse></soapenv:Body></soapenv:Envelope>";
	   resp =  resp.replaceAll("&", "&amp;");
	   System.out.println(resp);
	   if(!resp.equals("")) {
			Document doc = null;
		    doc = DocumentHelper.parseText(resp);
		    Element node = doc.getRootElement();
		    List<Element> element = getElement(node);
		    String url = "";
	    	String invoicedate = "";
	    	String invoiceCode = "";
	    	String invoiceNo = "";
	    	String invoiceId = "";
	    	String values = "";
	    	String type = "";
	    	String result = "";
			String jsonStr = "";
	        com.hp.bon.sgw.wh.bean.Invoice invoice = new com.hp.bon.sgw.wh.bean.Invoice();
		    for (int j = 0; j < element.size(); j++) {
		      Element element2 = element.get(j);
		      String name = element2.getName();
	    	  //_log.info("=======================1111========================");
	    	  if(name.equals("RESULT")) {
	    		  result = element2.getText();
	    	  }
	    	  if(name.equals("url")) {
	    		  url = element2.getText();
	    	  }
			  if(name.equals("invoiceDate")) {
				  invoicedate = element2.getText();	    		  
			  }
			  if(name.equals("invoiceCode")) {
				  invoiceCode = element2.getText();
			  }
			  if(name.equals("invoiceNo")) {
				  invoiceNo = element2.getText();
			  }
			  if(name.equals("invoiceId")) {
				  invoiceId = element2.getText();
			  }
             if(name.equals("value")) {
           	  values = element2.getText();
			  }
			  if(name.equals("type")) {
				  type = element2.getText();
			  }
		    
		    }
		    invoice.setInvoiceCode(invoiceCode);
	    	invoice.setInvoiceDate(invoicedate);
	    	invoice.setInvoiceId(invoiceId);
	    	invoice.setInvoiceNo(invoiceNo);;
	    	invoice.setType(type);
	    	invoice.setValue(values);
	    	invoice.setUrl(url);
	    	invoiceList.add(invoice);
	    	if(!result.equals("0")) {
	    		List<MonthlyBillError> monthlyBillErrorList = new ArrayList<MonthlyBillError>();
		    	MonthlyBillError monthlyBillError = new MonthlyBillError();
		    	monthlyBillError.setCode(result);
		    	monthlyBillError.setMessage("");
		    	monthlyBillError.setReason("");
		    	monthlyBillError.setReferenceError("");
		    	monthlyBillErrorList.add(monthlyBillError);
		    	jsonStr = JSON.toJSONString(monthlyBillErrorList);
		    	jsonStr = jsonStr.replaceAll("\\[", "");
			   	jsonStr = jsonStr.replaceAll("\\]", "");
		    }
		    else {
			    jsonStr = JSON.toJSONString(invoiceList);
			    jsonStr = jsonStr.replaceAll("\\[", "");
			   	jsonStr = jsonStr.replaceAll("\\]", "");
		    }
	    	System.out.println(jsonStr);
	   
	    		
   }
	   
	   
	  /* public static Map sortMapByKey(Map map){


		   if(map==null||map.isEmpty()){
		       return null;

		   Map sortMap=newTreeMap (newMapKeyComparator());


		   sortMap.putAll(map);


		   return sortMap;


		   }


	}*/
	
	  /* public class MapKeyComparator implements Comparator {


		   public int compare(String str1,String str2){


		   return str1.compareTo(str2);


		   }

		 (non-Javadoc)
		 * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
		 
		@Override
		public int compare(Object o1, Object o2) {
			return 0;
		}


	}
   private static List<Element> getElement(Element node) {
	    List<Element> list = node.elements();
	    if (list.size() > 0) {
	      for (int i = 0; i < list.size(); i++) {
	        //获取task下的所有子节点
	        Element element = list.get(i);
	        //遍历每一个子节点
	        if (!element.isTextOnly()) {
	          String name = element.getName();
	          if ("ITEM".equalsIgnoreCase(name)) {
	            System.out.println("attrName:" + name);
	            break;
	          } else {
	            list = getElement(element);
	          }
	        }
	      }
	    }
	    return list;
	  }
   
   public static List<String> findDaysStr(String begintTime, String endTime) {
		
	   begintTime = "20190121";
	   endTime = "20190123";
	    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		Date dBegin = null;
		Date dEnd = null;
		try {
			dBegin =  sdf.parse(begintTime);
			dEnd = sdf.parse(endTime);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		//存放每一天日期String对象的daysStrList 
		List<String> daysStrList = new ArrayList<String>();
               //放入开始的那一天日期String
		daysStrList.add(sdf.format(dBegin));

		Calendar calBegin = Calendar.getInstance();
		// 使用给定的 Date 设置此 Calendar 的时间
		calBegin.setTime(dBegin);

		Calendar calEnd = Calendar.getInstance();
		// 使用给定的 Date 设置此 Calendar 的时间
		calEnd.setTime(dEnd);

		// 判断循环此日期是否在指定日期之后
		while (dEnd.after(calBegin.getTime())) {
	    	// 根据日历的规则，给定的日历字段增加或减去指定的时间量
		    calBegin.add(Calendar.DAY_OF_MONTH, 1);
	        String dayStr = sdf.format(calBegin.getTime());
	    	daysStrList.add(dayStr);
		}

               //打印测试数据
               //System.out.println("#####################："+daysStrList);

		return daysStrList;
	}*/
   }
   private static List<Element> getElement(Element node) {
	    List<Element> list = node.elements();
	    if (list.size() > 0) {
	      for (int i = 0; i < list.size(); i++) {
	        //获取task下的所有子节点
	        Element element = list.get(i);
	        //遍历每一个子节点
	        if (!element.isTextOnly()) {
	          String name = element.getName();
	          if ("ITEM".equalsIgnoreCase(name)) {
	            System.out.println("attrName:" + name);
	            break;
	          } else {
	            list = getElement(element);
	          }
	        }
	      }
	    }
	    return list;
	  }

}
